<template>
  <div class="curriculum">
    <div class="curriculum_ind">
      <div class="aroundOf">基本信息</div>
      <b-container fluid>
        <b-row align-h="start" class="row" cols="24" cols-md="24">
          <b-col>
            <div>
              <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="课件名称：" prop="name">
                  <el-col :span="12">
                    <el-input v-model="ruleForm.name" maxlength="20" show-word-limit placeholder="请输入课件名称(建议字数在20个字以内，不超过20个字)"></el-input>
                  </el-col>
                  <span class="mandatory mandatoryBi">（必填）请输入20个字符以内的名称</span>
                </el-form-item>
                <el-form-item label="封面图片：" :rules="[{ required: true, message: '请上传图片', trigger: 'blur' }]">
                  <el-col :span="18">
                    <el-upload
                      ref="upload"
                      class="avatar-uploader"
                      :headers="config"
                      :action=" baseUrl + '/courseware/wareimg'"
                      _drag
                      :show-file-list="false"
                      accept="image/jpeg,image/jpg,image/png"
                      :before-upload="beforeAvatarUpload"
                      :on-success="handleAvatarSuccess"> 
                      <!-- :on-preview="handlePictureCardPreview" :on-remove="handleRemove"-->
                      <img v-if="ruleForm.img" :src="ruleForm.img" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon" style="background: #f9f9f9; border: 1px dashed #d9d9d9" ></i>
                      <p class="mandatory mandatory_rightsE" >（必填）请上传2M以内的文件，支持格式.jpg、.jpeg、.png</p>
                       <!-- style="margin: 60px 0 0 15px;" -->
                    </el-upload>
                    <!-- 放大的效果 -->
                    <!-- <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogVisible" alt="">
                    </el-dialog> -->
                  </el-col>
                </el-form-item>

                <div class="aroundOf resources">资源设置</div>
                <div class="resources">
                  <div class="resources_">
                    <el-form-item label="所属分类：" prop="fname">
                      <el-select v-model="ruleForm.fname" placeholder="请选择分类" clearable @change="chonseChang">
                        <el-option v-for="item in fname" :key="item.id" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                      <span class="resources-ls1" >（必选）只能选择一个分类</span>
                    </el-form-item>
                  </div>
                  <div class="resources-l" v-if="this.ruleForm.fname == 1 || this.ruleForm.fname == '理化生实验'">
                    <el-form-item label="所属学科：" :rules="[{ required: true, message: '请选择所属学科', trigger: 'blur' }]">
                      <el-select v-model="ruleForm.subject" placeholder="请选择学科" clearable>
                        <el-option v-for="item in subject" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                      <span class="resources-ls1" >（必选）只能选择一个学科</span>
                    </el-form-item>
                  </div>
                  <div class="resources-s" v-if="this.ruleForm.fname == 1 || this.ruleForm.fname == 2 || this.ruleForm.fname == '理化生实验' || this.ruleForm.fname == '数学几何'">
                    <el-form-item label="所属年级：" :rules="[{ required: true, message: '请选择所属年级', trigger: 'blur' }]">
                      <el-select v-model="ruleForm.clas" placeholder="请选择年级" clearable>
                        <el-option v-for="item in clas" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                      <span class="resources-ls1" >（必选）只能选择一个年级</span>
                    </el-form-item>
                  </div>

                  <div class="resources-s" v-show="this.ruleForm.fname == 4 || this.ruleForm.fname == '校园安全'">
                    <el-form-item label="二级分类：" :rules="[{ required: true, message: '请选择校园安全的二级分类', trigger: 'blur' }]">
                      <el-select v-model="ruleForm.campus" placeholder="请选择" clearable>
                        <el-option v-for="item in campus" :key="item.id" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                      <span class="resources-ls1" >（必选）只能选择一个校园安全的二级分类</span>
                    </el-form-item>
                  </div>

                  <div class="resources-s" v-if="this.ruleForm.fname == 5 || this.ruleForm.fname == '人文地理'">
                    <el-form-item label="二级分类：" :rules="[{ required: true, message: '请选择人文地理的二级分类', trigger: 'blur' }]">
                      <el-select v-model="ruleForm.humanities" placeholder="请选择" clearable @change="changeEr">
                        <el-option v-for="item in humanities" :key="item.id" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                      <span class="resources-ls1" >（必选）只能选择一个人文地理的二级分类</span>
                    </el-form-item>
                  </div>

                </div>
                
                <el-form-item label=" 上传文件：" >
                  <el-checkbox-group v-model="coursewarePattern" v-if="parent">
                    <el-checkbox label="教学模式"></el-checkbox>
                    <el-checkbox label="评测模式"></el-checkbox>
                  </el-checkbox-group>
                  
                  <el-upload
                    ref="upload"
                    class="upload-demo"
                    id="upload-demos"
                    drag
                    :headers="config"
                    :file-list="fileList"
                    :action=" baseUrl + '/courseware/warejian'"
                    :before-upload="beforeUploadFile"
                    :on-success="onSuccess"
                    :on-remove="onRemove"
                    :on-change="onChangeWen"
                    accept=".apk"
                    :limit="1" >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text"> 将文件拖到此处，或<em>点击上传</em></div>
                    <span class="el-upload__tip mandatory mandatoryIn" slot="tip" >（非必填）请上传500M以内的文件，支持格式apk</span>
                    <span v-if="isForward" class="isForward" slot="tip" style="color: #aaaaaa;">敬请期待</span>
                  </el-upload>
                </el-form-item>

                <div class="aroundOf resources">状态设置</div>
                <div class="state_in">
                  <el-form-item label="">
                    <el-radio-group v-model="ruleForm.status" @change="changeStatus">
                      <template v-if="itemGet == 'add'">
                        <el-radio label="立即上架"></el-radio>
                        <el-radio label="暂不上架"></el-radio>
                      </template>
                      <template v-else>
                        <el-radio label="立即上架"></el-radio>
                        <el-radio label="暂不上架"></el-radio>
                        <el-radio label="下架"></el-radio>
                      </template>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')" class="complete" >完 成</el-button>
                </el-form-item>
              </el-form>
            </div>
          </b-col>
        </b-row>
      </b-container>
    </div>
   
  </div>
</template>

<script>
import { base } from '../../api/axiosFun';
export default {
  data() {
    return {
      baseUrl: '',  // 请求地址
      fname: [], // 这个是全部分类的一级分类
      subject:[{ value: '物理', label: '物理' },{ value: '化学', label: '化学' },{value: '生物',label: '生物'}],
      clas: [ { value: '初一上', label: '初一上' },{ value: '初一下', label: '初一下' },{ value: '初二上', label: '初二上' },{ value: '初二下', label: '初二下' },{ value: '初三上', label: '初三上' },{ value: '初三下', label: '初三下' } ],
      campus: [], // 这个是校园安全的二级分类
      humanities: [], // 这个是人文地理的二级分类
      ruleForm: {
        name: "",
        img: "",   // 上传的图片
        fname: '',
        subject: '',
        clas: '',
        wen: '',  // 上传的apk文件
        capacity: '',  //文件大小
        wename: '',
        status: '',  //  状态设置
        campus: '', // 校园安全
        humanities: '', // 人文地理
        md5: '',
      },
      coursewarePattern: [],
      parent: false,  // 控制两种模式的显隐
      // 校验
      rules: {
        name: [
          { required: true, message: "请输入课件名称(建议字数在20个字以内，不超过20个字)", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
        ],
        fname: [{ required: true, message: "请选择所属分类", trigger: "blur" }],
      },
      time: '',  //  上传文件的时间
      fileList: [],
      newVal: '',
      dialogVisible: false,   // 放大的效果
      loading: false,  //  加载进度条初始值
      isForward: true, // 控制上传文件的敬请期待
      Authorization: localStorage.getItem("logintoken"),  //  上传文件携带token  Authorization这个是键
      file: {},  // 判断文件上传成功才能点
      itemGet: '',
    };
  },
  computed: {
    config() {
      return { Authorization: this.Authorization };
    },
  },
  mounted() {
    this.baseUrl = base;
    this.itemGet = sessionStorage.getItem('add');// console.log(this.baseUrl,sessionStorage.getItem('add'))
    // console.log(JSON.parse(sessionStorage.getItem('curriculm')),this.$route.params.add) //  传递过来的数据编辑数据 uploadImge
    if(sessionStorage.getItem('add') != 'add'){ // 判断是新增进来的还是编辑进来的 获取数据
      this.allCategories();
      this.ruleForm = JSON.parse(sessionStorage.getItem('curriculm'));
      if(JSON.parse(sessionStorage.getItem('curriculm')).status == 1) { this.ruleForm.status = sessionStorage.getItem('statusChange') } 
      else if(JSON.parse(sessionStorage.getItem('curriculm')).status == 3){ this.ruleForm.status = sessionStorage.getItem('statusChange') } 
      else { this.ruleForm.status = sessionStorage.getItem('statusChange') }
      this.fileList = JSON.parse(sessionStorage.getItem('curriculm')).wenn;
      this.time = JSON.parse(sessionStorage.getItem('curriculm')).shDate;
      // this.ruleForm.campus = JSON.parse(sessionStorage.getItem('curriculm')).tname;
      // this.ruleForm.humanities = JSON.parse(sessionStorage.getItem('curriculm')).tname;
      this.$set(this.ruleForm,'campus',JSON.parse(sessionStorage.getItem('curriculm')).tname)    // 这里用到的$set是因为vue监听不到传过来的数据
      this.$set(this.ruleForm,'humanities',JSON.parse(sessionStorage.getItem('curriculm')).tname)
      if(JSON.parse(sessionStorage.getItem('curriculm')).fname == "理化生实验" || JSON.parse(sessionStorage.getItem('curriculm')).wem !='' && JSON.parse(sessionStorage.getItem('curriculm')).wename != '') {
        this.parent = true;
        const newPattern = JSON.parse(sessionStorage.getItem('curriculm')).pattern;  // 回显的上传文件多选
        if(newPattern != undefined) {
          this.coursewarePattern = newPattern.split(','); // 字符串转为数组
        } else {
          this.parent = false;
        }
      }  else { this.parent = false; }
      if(JSON.parse(sessionStorage.getItem('curriculm')).wenn != undefined){
        if(this.fileList.length == 0) { this.isForward = true; } 
        else { this.isForward = false; }
        this.parent = true;
      }
    } else {
      if(this.fileList.length == 0) { this.isForward = true; }
      this.allCategories();
    }
  },
  methods: {
    // 获取全部分类
    allCategories() {
      this.$http.content.allCategories().then( res => {
        this.fname = res.data.splice(0, 5);
        this.campus = res.data.splice(0, 5);
        this.humanities = res.data;
      })
    },
    // 图片上传
    handleAvatarSuccess(res, file){
      this.time = res.data.time;
      this.ruleForm.img = res.data.url;
      // this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
    },
    // 上传图片
    beforeAvatarUpload(files) {
      const isLt2M = files.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    changeEr(val) { // 人文地理二级分类选择
      this.ruleForm.humanities = val;
    },
    // 这个是文件上传成功后
    onSuccess(response, file, fileList){ 
      // console.log(response, file, fileList)
      this.parent = true;
      this.isForward = false;  // 上传成功后隐藏敬请期待
      this.ruleForm.wen = response.data.url;
      // this.ruleForm.wename = response.data.name.split('.apk')[0];
      const AppInfoParser = require('app-info-parser');  // 文件流
      const parser = new AppInfoParser(file.raw); // or xxx.ipa
      parser.parse().then(result => {
        this.ruleForm.wename = result.package;
        // console.log('app info ----> ', result) // console.log('icon base64 ----> ', result.icon)
      }).catch(err => { console.log('err ----> ', err) })
      this.ruleForm.capacity = response.data.capacity / 1024 / 1024;   // 这个是上传的.apk文件的大小
      this.ruleForm.md5 = response.data.md5;
      this.$notify({ title: '上传成功', type: 'success' });
    },
    // 上传文件限制
    beforeUploadFile(file){
      this.$notify({
        title: '正在上传文件，请稍后',
        duration: 6000,
        type: 'warning'
      });
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const size = file.size / 1024 / 1024;
      if (extension !== 'apk') {
        this.$notify.warning({
          title: '警告',
          message: `只能上传（即后缀是.apk）的文件`
        })
        this.fileList = []; //  如果不是.apk的文件就把这个数组给置空
      }
      if (size > 500) {
        this.$notify.warning({
          title: '警告',
          message: `文件大小不得超过500M`
        })
      }
    },
    // 清除上传文件时移除下方进度条  //目前后台是不能删除数据的  删除后编辑进去还是会有的 后续再出
    onRemove(file, fileList){ 
      this.loading = false; 
      if(fileList.length == 0) {
        this.parent = false;
        this.ruleForm.wen = '';
        this.ruleForm.wename = '';
        this.coursewarePattern = [];
        this.ruleForm.capacity = 0;
      }
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    onChangeWen(file, fileList){ this.file = file.response; },

    chonseChang(val) {  // 请选择分类
      if(val == 1){ this.ruleForm.subject = '',this.ruleForm.clas = '',this.parent = true; }
      else if(val == 2) { this.ruleForm.clas = '',this.parent = false; }
      else if(val == 4) { this.ruleForm.campus = '',this.parent = false; }
      else if(val == 5){ this.ruleForm.humanities = '',this.parent = false; }
      else { this.parent = false }
    },
    // 状态设置切换
    changeStatus(val){ sessionStorage.setItem('statusChange', val); },
    // 完成按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if(this.ruleForm.img == ''){
          this.$message({
            message: '警告,请上传图片',
            type: 'warning'
          });
        }
        this.ruleForm.status = sessionStorage.getItem('statusChange'); // 保存你所选的状态设置
        if (valid) {
          if(this.ruleForm.status == '立即上架') { this.newVal = this.ruleForm.status = 1;} 
          else if(this.ruleForm.status == '暂不上架') { this.newVal = this.ruleForm.status = 3; } 
          else { this.newVal = this.ruleForm.status = 2; }
          if(this.itemGet == 'add') {  // 这个是新增进来的添加
            if(this.ruleForm.wen != '' && this.ruleForm.wename != '' && this.coursewarePattern.length == 0)  {
              this.$message({
                message: '请选择教学模式或者评测模式',
                type: 'warning'
              });
              this.ruleForm.status = sessionStorage.getItem('statusChange');  // 保存你所选的状态设置
            } else if(this.ruleForm.name != '' && this.ruleForm.img != '' && this.ruleForm.fname != '' && this.newVal != '') {
              this.$http.content.newCourseware({
                name: this.ruleForm.name,
                img: this.ruleForm.img,
                wen: this.ruleForm.wen,
                wename: this.ruleForm.wename,
                capacity: this.ruleForm.capacity,
                fid: this.ruleForm.fname,
                subject: this.ruleForm.subject,
                clas: this.ruleForm.clas,
                status: this.newVal,
                shDate: this.time,
                tid: this.ruleForm.campus || this.ruleForm.humanities,
                pattern: this.coursewarePattern.toString(),
                md: this.ruleForm.md5
              }).then( res => {
                this.$message({
                  message: '恭喜你，保存成功',
                  type: 'success'
                });
                sessionStorage.removeItem('statusChange');
                setTimeout( () => {
                  this.$router.go(-1);
                  this.ruleForm = {
                    name: "",
                    img: "",   // 上传的图片
                    fname: '',
                    subject: '',
                    clas: '',
                    wen: '',  //上传的apk文件
                    wename: '',
                    status: '',  //  状态设置
                    campus: '', // 校园安全
                    humanities: '' // 人文地理
                  }
                  sessionStorage.removeItem('curriculm');
                  sessionStorage.removeItem('add');
                },500)
              })
            }
          } else {  // 编辑修改过来的
            if(this.ruleForm.wen != '' && this.ruleForm.wename != '' && this.coursewarePattern.length == 0)  {
              this.$message({
                message: '请选择教学模式或者评测模式',
                type: 'warning'
              });
              this.ruleForm.status = sessionStorage.getItem('statusChange'); // 保存你所选的状态设置
            } else if(this.ruleForm.name != '' && this.ruleForm.img != '' && this.ruleForm.fname != '' && this.newVal != '') {
              if(this.ruleForm.fname == 4) { 
                this.ruleForm.subject = '';
                this.ruleForm.clas = '';
                this.ruleForm.humanities = '';
              } else if(this.ruleForm.fname == 5) {
                this.ruleForm.subject = '';
                this.ruleForm.clas = '';
                this.ruleForm.campus = '';
              } 
              else if(this.ruleForm.fname == 3) { 
                this.ruleForm.campus = '';
                this.ruleForm.humanities = '';
                this.ruleForm.subject = '' ;
                this.ruleForm.clas = '';
              } else if(this.ruleForm.fname == 2) { this.ruleForm.subject = '';this.ruleForm.campus = '';this.ruleForm.humanities = ''; }
              else if(this.ruleForm.fname = 1) { this.ruleForm.campus = '';this.ruleForm.humanities = ''; }
              this.$http.content.newCourseware({
                id: JSON.parse(sessionStorage.getItem('curriculm')).id,
                name: this.ruleForm.name,
                img: this.ruleForm.img,
                wen: this.ruleForm.wen,
                wename: this.ruleForm.wename,
                capacity: this.ruleForm.capacity,
                fid: this.ruleForm.fname,
                subject: this.ruleForm.subject,
                clas: this.ruleForm.clas,
                status: this.newVal,
                shDate: this.time,
                tid: this.ruleForm.campus || this.ruleForm.humanities,
                pattern: this.coursewarePattern.toString() ,
                md: this.ruleForm.md5
              }).then( res => {// console.log(res)
                this.$message({
                  message: '恭喜你，修改成功',
                  type: 'success'
                });
                sessionStorage.removeItem('statusChange');
                setTimeout( () => {
                  this.$router.push({ path: '/content' })
                  this.ruleForm = {
                    name: "",
                    img: "",   // 上传的图片
                    fname: '',
                    subject: '',
                    clas: '',
                    wen: '',  //上传的apk文件
                    wename: '',
                    status: '',  //  状态设置
                    campus: '', // 校园安全
                    humanities: '' // 人文地理
                  }
                  sessionStorage.removeItem('curriculm')
                },500)
              })
            } else {
              this.$message({
                message: res.errorMessage,
                type: 'warning'
              });
            }
          }
        }
      });
    },
  },
};
</script>

<style scoped>
@import '../../assets/css/content/curriculum.scss';
</style>